package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.XbbConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchBoardConditionDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataInConditionDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataSetInConditionDTO;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.bi.DataSetNodeTypeEnum;
import com.xbongbong.paas.factory.OptionFactory;
import com.xbongbong.paas.feign.WorkOrderClient;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.handle.AbstractOptionHandle;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.analysis.data.FormDataLinkDataListAnalysisDataHelp;
import com.xbongbong.paas.manager.feign.ChartLinkFeignClient;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.BusinessRulesPoJo;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.dto.BusinessFormDataDTO;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateBatchDTO;
import com.xbongbong.paas.pojo.dto.SearchInConditionDTO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.pojo.vo.LinkFormDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.SearchDataInConditionVO;
import com.xbongbong.paas.service.ConditionListService;
import com.xbongbong.paas.service.DistinctDataService;
import com.xbongbong.paas.service.ProFormDataService;
import com.xbongbong.paas.service.impl.base.BaseFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.TitleUtil;
import com.xbongbong.pro.businessdata.pojo.dto.SpecificationHistoryDTO;
import com.xbongbong.pro.businessdata.pojo.vo.SpecificationHistoryVO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.domain.entity.DataSetEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.BiErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.SpecificationDTO;
import com.xbongbong.pro.formdata.pojo.vo.FieldExistDataVO;
import com.xbongbong.pro.formdata.pojo.vo.OtherDataListVO;
import com.xbongbong.pro.formexplain.pojo.ConditionExplainPojo;
import com.xbongbong.pro.statistic.model.DataSetModel;
import com.xbongbong.pro.statistic.pojo.ChartFieldAttrPojo;
import com.xbongbong.pro.statistic.result.pojo.dto.ChartLinkDTO;
import com.xbongbong.pro.weblist.pojo.dto.SaasBaseDTO;
import com.xbongbong.pro.weblist.pojo.vo.WaitNumberVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.SaasFieldConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DistributorAccountEntity;
import com.xbongbong.saas.domain.entity.KnowledgeDataEntity;
import com.xbongbong.saas.domain.entity.KnowledgeTagEntity;
import com.xbongbong.saas.domain.entity.ProductSerialBalanceEntity;
import com.xbongbong.saas.domain.entity.SpecificationValueEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.PaymentSourceTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.BatchFlowBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.KnowledgeDataEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductSerialBalanceEnum;
import com.xbongbong.saas.enums.business.StockFlowBillEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.product.PriceSetEnum;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.KnowledgeDataModel;
import com.xbongbong.saas.model.KnowledgeTagModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialBalanceModel;
import com.xbongbong.saas.model.SpecificationValueModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.service.ScoreRangeService;
import com.xbongbong.sys.domain.entity.PriceSetEntity;
import com.xbongbong.sys.model.PriceSetModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/7/4 10:41
 * @since v1.0
 */
@Service("proFormDataService")
public class ProFormDataServiceImpl extends BaseFormDataService implements ProFormDataService {

    private static final Logger LOG = LoggerFactory.getLogger(ProFormDataService.class);

    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private DistinctDataService distinctDataService;
    @Resource
    private SpecificationValueModel specificationValueModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private FormDataLinkDataListAnalysisDataHelp formDataLinkDataListAnalysisDataHelp;
    @Resource
    private OptionFactory optionFactory;
    @Resource
    private ConditionListService conditionListService;
    @Resource
    private ProductSerialBalanceModel productSerialBalanceModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PriceSetModel priceSetModel;
    @Resource
    private ScoreRangeService scoreRangeService;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private KnowledgeDataModel knowledgeDataModel;
    @Resource
    private KnowledgeTagModel knowledgeTagModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private DataSetModel dataSetModel;
    @Resource
    private ChartLinkFeignClient chartLinkFeignClient;
    @Resource
    private PaasBatchEditService paasBatchEditService;

    @Resource
    private WorkOrderClient workOrderClient;



    /**
     * 检验能否不可见或不启用规格字段
     * @param specificationDTO
     * @return
     * @throws XbbException
     */
    @Override
    public FieldExistDataVO canDeleteSpecification(SpecificationDTO specificationDTO) throws XbbException{
        FieldExistDataVO fieldExistDataVO = new FieldExistDataVO();
        fieldExistDataVO.setCanDelete(true);
        String corpid = specificationDTO.getCorpid();
        Map<String,Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID,corpid);
        params.put(ParameterConstant.DEL,DelEnum.NORMAL.getDel());
        Integer totalCount = productModel.getEntitysCount(params);
        LOG.warn("corpid:" + corpid + "数据库中共有产品" + totalCount + "条数据");
        int pageSize = 500;
        int totalPage = (totalCount % pageSize == 0) ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        int lastPageSize = (totalCount % pageSize == 0) ? pageSize : (totalCount % pageSize);
        Loop : for (int page = 0; page < totalPage; page++) {
            if (page == totalPage - 1) {
                params.put("pageNum", lastPageSize);
            } else {
                params.put("pageNum", pageSize);
            }
            params.put("start", page * pageSize);
            LOG.warn("第" + page + "页开始");
            List<ProductEntityExt> productEntityExtList = productModel.findEntitys(params);
            if (productEntityExtList.isEmpty()) {
                continue;
            }
            for (ProductEntityExt productEntityExt : productEntityExtList) {
                JSONObject data = productEntityExt.getData();
                Integer specification = data.getInteger(ProductEnum.SPECIFICATION.getAttr());
                if (Objects.equals(specification,1)){
                    fieldExistDataVO.setCanDelete(false);
                    fieldExistDataVO.setMsg(String.format(ProductErrorCodeEnum.API_ERROR_205046.getMsg(),Objects.equals(specificationDTO.getOperation(),1) ? I18nMessageUtil.getMessage(I18nStringConstant.DELETE_SPECIFICATION_FIELD) : I18nMessageUtil.getMessage(I18nStringConstant.SET_INVISIBLE)));
                    break Loop;
                }
            }
        }
        return fieldExistDataVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBatch(FormDataUpdateBatchDTO formDataUpdateBatchDTO, PaasFormEntityExt paasFormEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
       paasBatchEditService.updateBatch(formDataUpdateBatchDTO, paasFormEntityExt, explainMap);
    }

    /**
     * 校验是否有 无权限编辑者编辑了数据
     * @param formDataUpdateBatchDTO
     * @param paasFormEntityExt
     * @param explainMap
     * @param list
     * @throws XbbException
     */
    private void validateTeamMembersCheckEditPermission(FormDataUpdateBatchDTO formDataUpdateBatchDTO, PaasFormEntityExt paasFormEntityExt, Map<String, FieldAttrEntity> explainMap, List<PaasFormDataEntityExt> list) throws XbbException {
        paasBatchEditService.validateTeamMembersCheckEditPermission(formDataUpdateBatchDTO, paasFormEntityExt, explainMap, list);
    }

    private String getTitle(List<FormTitlePoJo> formTitleList) {
       return TitleUtil.getTitle(formTitleList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataDeleteBatchVO deleteBatch(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<BusinessRulesPoJo> businessRules) throws XbbException {
        FormDataDeleteBatchVO formDataDeleteBatchVO = new FormDataDeleteBatchVO();
        try {
            paasFormDataModel.deleteBatch(formDataDeleteBatchDTO.getDataIdList(), formDataDeleteBatchDTO.getCorpid(), DelEnum.DELETE.getDel());
            // 业务规则逻辑 start
//            if(Objects.nonNull(businessRules) && !businessRules.isEmpty()){
//                InactiveRuleByDeleteBatchDTO inactiveRuleDTO = new InactiveRuleByDeleteBatchDTO();
//                BeanUtil.copyProperties(formDataDeleteBatchDTO, inactiveRuleDTO);
//                inactiveRuleDTO.setRuleList(businessRules);
//                inactiveRuleDTO.setFormDataIdList(formDataDeleteBatchDTO.getDataIdList());
//                    formDataInactiveRuleByDeleteBatchHelp.inactiveRuleByDeleteBatch(inactiveRuleDTO);
//            }
            // 业务规则逻辑 end
        }catch (Exception e) {
            LOG.error("proFormDataService.deleteBatch 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataDeleteBatchVO;
    }

    @Override
    public WaitNumberVO waitNumber(SaasBaseDTO saasBaseDTO) throws XbbException {
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(XbbRefTypeEnum.transferBusinessType4Distributor(saasBaseDTO.getSubBusinessType(),saasBaseDTO.getDistributorMark()));
        Integer waitNumber = 0;
        switch (xbbRefTypeEnum){
            case PURCHASE:
                // 待采购总数获取已经不支持，这里返回默认0，看web端有没有调用场所
                waitNumber = 0;
                break;
            case PRODUCTION_ORDER:
                waitNumber = saasListHelp.getWaitProduceCount(saasBaseDTO.getLoginUser());
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
                waitNumber = saasListHelp.getWaitInstock(saasBaseDTO.getLoginUser());
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
                waitNumber = saasListHelp.getWaitOutstock(saasBaseDTO.getLoginUser(),saasBaseDTO.getDistributorMark());
                break;
            case WORK_ORDER:
                waitNumber = saasListHelp.getWaitRob(saasBaseDTO.getLoginUser()).intValue();
                break;
            case ORDER_OUTSTOCK:
                waitNumber = saasListHelp.getWaitOutstock(saasBaseDTO.getLoginUser(),DistributorMarkEnum.DISTRIBUTOR.getCode());
                break;
            default:
                break;
        }
        WaitNumberVO waitNumberVO = new WaitNumberVO();
        waitNumberVO.setWaitNumber(waitNumber);
        return waitNumberVO;
    }

    @Override
    public SpecificationHistoryVO specificationHistory(SpecificationHistoryDTO specificationHistoryDTO) throws XbbException {
        SpecificationHistoryVO specificationHistoryVO = new SpecificationHistoryVO();
        String corpid = specificationHistoryDTO.getCorpid();
        String specification = specificationHistoryDTO.getSpecification();
        List<String> excludeSpecification = specificationHistoryDTO.getExcludeSpecification();
        List<String>  excludeSpecificationValue = specificationHistoryDTO.getExcludeSpecificationValue();
        Map params = new HashMap(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put("corpid",corpid);
        params.put("del",0);
        params.put("nameLike",StringUtil.isEmpty(specificationHistoryDTO.getNameLike()) ? null :  specificationHistoryDTO.getNameLike());
        if (!(Objects.isNull(specification) || specification.isEmpty())){
            params.put("specificationKey",specification);
        }
        Set<String> items = new LinkedHashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<String> retItems = items;
        PageHelper pageHelper = new PageHelper(1,5);
        List<SpecificationValueEntity> specificationValueEntities = (List<SpecificationValueEntity>) PageHelperUtil.getEntityList(params, pageHelper, specificationValueModel);
        if (Objects.isNull(specification) || specification.isEmpty()){
            specificationValueEntities.forEach(item -> items.add(item.getSpecificationKey()));
        } else {
            specificationValueEntities.forEach(item -> items.add(item.getSpecificationValue()));
        }
        if (CollectionsUtil.isNotEmpty(excludeSpecification)){
            for (String spec : excludeSpecification){
                retItems.removeIf(item -> Objects.equals(item,spec));
            }
        }
        if (CollectionsUtil.isNotEmpty(excludeSpecificationValue)){
            for (String specValue : excludeSpecificationValue){
                retItems.removeIf(item -> Objects.equals(item,specValue));
            }
        }
        specificationHistoryVO.setItems(retItems);
        return specificationHistoryVO;
    }

    @Override
    public SearchDataInConditionVO dataSetConditionList(SearchDataSetInConditionDTO searchDataSetInConditionDTO) throws XbbException {
        //TODO  入参条件的拼装
        DataSetEntity dataSet = dataSetModel.getByKey(searchDataSetInConditionDTO.getDataSetId(), searchDataSetInConditionDTO.getCorpid());
        JSONObject boardJson = dataSet.getBoard();
        return dataSetConditionList(searchDataSetInConditionDTO, boardJson,false);
    }

    @Override
    public SearchDataInConditionVO dataSetConditionList(SearchBoardConditionDTO searchBoardConditionDTO) throws XbbException {
        return dataSetConditionList(searchBoardConditionDTO, searchBoardConditionDTO.getJsonStr(),true);
    }

    /**
     *
     * @param searchDataSetInConditionDTO
     * @param boardJson
     * @param preView 是否是画布预览
     * @return
     * @throws XbbException
     */
    private SearchDataInConditionVO dataSetConditionList(SearchBoardConditionDTO searchDataSetInConditionDTO, JSONObject boardJson,boolean preView) throws XbbException {
        String attr = searchDataSetInConditionDTO.getAttr();
        JSONObject fieldJson = null;
        boolean unionFlag = false;
        String eqAttr = attr;
        if(attr.contains(".")){
            String[] av = attr.split("\\.");
            eqAttr = av[0];
        }
        if(preView){
            for (String s : boardJson.keySet()) {
                JSONObject json = boardJson.getJSONObject(s);
                if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.UNION.getAlias())){
                    unionFlag = true;
                    break;
                }
            }
            JSONObject preNodeJson = boardJson.getJSONObject(searchDataSetInConditionDTO.getInputId());
            JSONArray fields = preNodeJson.getJSONArray(XbbConstant.DS_FIELD);
            for (int i = 0; i < fields.size(); i++) {
                JSONObject field = fields.getJSONObject(i);
                if(Objects.equals(eqAttr,field.getString("attr"))){
                    fieldJson = field;
                    if(StringUtil.isEmpty(fieldJson.getString(XbbConstant.TYPE))){
                        fieldJson.put(XbbConstant.TYPE,preNodeJson.getString(XbbConstant.TYPE));
                    }
                    break;
                }
            }
        }else {
            for (String s : boardJson.keySet()) {
                JSONObject json = boardJson.getJSONObject(s);
                if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.OUTPUT.getAlias())){
                    //输出节点直接去找他的input
                    String  preNodeId  = json.getJSONArray(DataSetNodeTypeEnum.INPUT.getAlias()).getString(BasicConstant.ZERO);
                    JSONObject preNodeJson = boardJson.getJSONObject(preNodeId);
                    JSONArray fields = preNodeJson.getJSONArray(XbbConstant.DS_FIELD);
                    for (int i = 0; i < fields.size(); i++) {
                        JSONObject field = fields.getJSONObject(i);
                        if(Objects.equals(eqAttr,field.getString("attr"))){
                            fieldJson = field;
                            break;
                        }
                    }
                }else if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.UNION.getAlias())){
                    unionFlag = true;
                }
            }
        }

        if(unionFlag){
            //有合并的
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(searchDataSetInConditionDTO.getFieldType());
            switch (fieldTypeEnum){
                case COMBO:
                case STAR:
                case SWITCH:
                    //这3种只会出现在倒数第二个节点的源节点里
                    JSONObject inputJson = findInpuJointField(fieldJson, boardJson);
                    inputJson.remove(XbbConstant.TYPE);
                    ChartFieldAttrPojo chartFieldAttrPojo = JSONObject.parseObject(inputJson.toJSONString(), ChartFieldAttrPojo.class);
                    String originalAttr = chartFieldAttrPojo.getOriginalAttr();
                    if(StringUtil.isEmpty(originalAttr)){
                        originalAttr = attr;
                    }
                    searchDataSetInConditionDTO.setAttr(originalAttr);
                    searchDataSetInConditionDTO.setFormId(chartFieldAttrPojo.getFormId());
                    searchDataSetInConditionDTO.setSaasMark(chartFieldAttrPojo.getSaasMark());
                    searchDataSetInConditionDTO.setBusinessType(chartFieldAttrPojo.getBusinessType());
                    break;
                case TEXT_CHECK:
                case WORK_ORDER_STATUS:
                case LABEL:
                case PUBLIC_GROUP:
                    //TODO
                    break;
                case SERIALNO:
                case LINK_BUSINESS_SINGLE:
                case LINK_BUSINESS_MULTI:
                default:
                    //TODO   直接去查结果集 或者通过预览的方式处理
                    //拿到数据集id走查询表的逻辑
                    ChartLinkDTO chartLinkDTO = new ChartLinkDTO();
                    BeanUtil.copyProperties(searchDataSetInConditionDTO, chartLinkDTO, true);
                    chartLinkDTO.setPreView(preView);
                    XbbResponse<Object> diyResponse = chartLinkFeignClient.chartLinkResult(chartLinkDTO);
                    SearchDataInConditionVO searchDataInConditionVO = null;
                    if (diyResponse != null ) {
                        if(diyResponse.isSuccess()){
                            searchDataInConditionVO = JSONObject.parseObject(JSON.toJSONString(diyResponse.getResult(), SerializerFeature.DisableCircularReferenceDetect), SearchDataInConditionVO.class);
                        }else {
                            throw  new XbbException(diyResponse.getCode(),diyResponse.getMsg());
                        }
                    }
                    return searchDataInConditionVO;
            }
        }else {
            JSONObject inputJson = findInpuJointField(fieldJson, boardJson);
            if(inputJson == null || inputJson.isEmpty()){
                throw new XbbException(BiErrorCodeEnum.API_ERROR_241041);
            }
            inputJson.remove(XbbConstant.TYPE);
            ChartFieldAttrPojo chartFieldAttrPojo = JSONObject.parseObject(inputJson.toJSONString(), ChartFieldAttrPojo.class);
            String originalAttr = chartFieldAttrPojo.getOriginalAttr();
            if(StringUtil.isEmpty(originalAttr)){
                originalAttr = attr;
            }
            searchDataSetInConditionDTO.setAttr(originalAttr);
            searchDataSetInConditionDTO.setFormId(chartFieldAttrPojo.getFormId());
            searchDataSetInConditionDTO.setSaasMark(chartFieldAttrPojo.getSaasMark());
            searchDataSetInConditionDTO.setBusinessType(chartFieldAttrPojo.getBusinessType());
        }

        return dataConditionList(searchDataSetInConditionDTO);
    }



    /**
     * 找到原始字段
     * @param fieldJson  字段载体
     * @param boardJson 数据集board
     * @return
     */
    private JSONObject findInpuJointField(JSONObject fieldJson, JSONObject boardJson) throws XbbException {
        if(fieldJson !=null){
            if(Objects.equals(fieldJson.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.INPUT.getAlias())){
                //TODO  走不进来
                return fieldJson;
            }else if(Objects.equals(fieldJson.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.OUTPUT.getAlias())){
                //输出节点在前面处理过了
                throw new XbbException(BiErrorCodeEnum.API_ERROR_241041);
            }else{
                //非输入、输出节点的处理
                JSONObject srcB = fieldJson.getJSONObject("srcB");
                String nodeId = srcB.keySet().toArray()[0].toString();
                JSONObject json = boardJson.getJSONObject(nodeId);
                JSONObject jsonObject = srcB.getJSONObject(nodeId);
                if(Objects.equals(json.getString(XbbConstant.TYPE), DataSetNodeTypeEnum.INPUT.getAlias())){
                    jsonObject.put("businessType",json.getInteger("businessType"));
                    return jsonObject;
                }
                JSONArray fields = json.getJSONArray("field");
                for (int i = 0; i < fields.size(); i++) {
                    JSONObject field = fields.getJSONObject(i);
                    if(Objects.equals(jsonObject.getString("originalAttr"),field.getString("attr"))){
                        fieldJson = field;
                        break;
                    }
                }
                return  findInpuJointField(fieldJson, boardJson);
            }
        }
        return fieldJson;
    }

    @Override
    public SearchDataInConditionVO dataConditionList(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT_PRODUCT.getCode())) {
                return searchDataInConditionVO;
            }else if(Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT_PERFORMANCE.getCode())){
                if(Objects.equals(searchDataInConditionDTO.getFieldType(),FieldTypeEnum.COMBO_NUM.getType())){
                    List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                    itemDataPoJoList.add(new ItemDataPoJo("是","1"));
                    itemDataPoJoList.add(new ItemDataPoJo("否","0"));
                    searchDataInConditionVO.setItems(itemDataPoJoList);
                }
                return searchDataInConditionVO;
            } else if (Objects.equals(XbbRefTypeEnum.SLA_LOG.getCode(),searchDataInConditionDTO.getBusinessType())) {
                if ("text_1".equals(searchDataInConditionDTO.getAttr()) || "text_2".equals(searchDataInConditionDTO.getAttr())) {
                    // sla日志筛选特殊处理,放在这里情非得已，首先不应放在pro项目，其次移动端和web端不一致。。
                    List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                    setSpecialItemsForSla(searchDataInConditionDTO,itemDataPoJoList);
                    searchDataInConditionVO.setItems(itemDataPoJoList);
                    return searchDataInConditionVO;
                }
            } else if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_NODE_LOG_INFO.getCode(), searchDataInConditionDTO.getBusinessType())) {
                List<ItemDataPoJo> itemDataPoJoList = getItemData4NodeLogInfo(searchDataInConditionDTO);
                searchDataInConditionVO.setItems(itemDataPoJoList);
                return searchDataInConditionVO;
            }
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(searchDataInConditionDTO.getFieldType());
            ListGroupEnum listGroupEnum = ListGroupEnum.UNKONW;
            if (Objects.nonNull(searchDataInConditionDTO.getListGroupId())) {
                listGroupEnum = ListGroupEnum.getByCode(Math.toIntExact(searchDataInConditionDTO.getListGroupId()));
            }
            ConditionExplainPojo conditionExplainPojo = null;
            FieldAttrEntity fieldAttrEntity = new FieldAttrEntity();
            if (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.SIGNIN.getCode()) && !Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())
                && (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.STOCK_FLOW_BILL.getCode()) || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.STOCK_FLOW_BILL.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), StockFlowBillEnum.TYPE.getAttr())))
                    && (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.BATCH_FLOW_BILL.getCode()) || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.BATCH_FLOW_BILL.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), BatchFlowBillEnum.TYPE.getAttr())))
                    && (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.SEQ_SEARCH.getCode()) || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.SEQ_SEARCH.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), ProductSerialBalanceEnum.SEQ.getAttr())))
                    && (!Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode()) || (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode()) && Objects.equals(searchDataInConditionDTO.getAttr(), ProductEnum.WAREHOUSE.getSaasAttr())))
                    && (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode()) || (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode()) && (Objects.equals(searchDataInConditionDTO.getAttr(), ProductEnum.NAME.getAttr()) || Objects.equals(searchDataInConditionDTO.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr()))))
                    && (!Objects.equals(searchDataInConditionDTO.getAttr(), PaymentSourceTypeEnum.INVOICE.getAttr()) && !Objects.equals(searchDataInConditionDTO.getAttr(), PaymentSourceTypeEnum.OUTSTOCK.getAttr()))
                    && (!Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT_COMPARE_RESULT.getCode()))) {
                if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode()) || Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getCorpid());
                    searchDataInConditionDTO.setFormId(paasFormEntityExt.getId());
                    searchDataInConditionDTO.setAttr(ProductEnum.WAREHOUSE.getAttr());
                }
                if(Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.STOCK_SEARCH.getCode())){
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getCorpid());
                    searchDataInConditionDTO.setFormId(paasFormEntityExt.getId());
                }
                if(Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(searchDataInConditionDTO.getSubBusinessType(),XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())){
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getCorpid());
                    searchDataInConditionDTO.setFormId(paasFormEntityExt.getId());
                }
                if(Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode()) || Objects.equals(searchDataInConditionDTO.getPriceBusinessType(),XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())){
                    if (Objects.equals(searchDataInConditionDTO.getAttr(), PriceSetEnum.ADAPTER_TYPE.getAttr())) {
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), searchDataInConditionDTO.getCorpid());
                        searchDataInConditionDTO.setFormId(paasFormEntityExt.getId());
                        searchDataInConditionDTO.setBusinessType(paasFormEntityExt.getBusinessType());
                        searchDataInConditionDTO.setAttr(CustomerManagementEnum.NAME.getAttr());
                        searchDataInConditionDTO.setFieldType(CustomerManagementEnum.NAME.getFieldType());
//                        fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(searchDataInConditionDTO.getFieldType());
                    } else {
                        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), searchDataInConditionDTO.getCorpid());
                        searchDataInConditionDTO.setFormId(paasFormEntityExt.getId());
                        searchDataInConditionDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
                    }

                }
                conditionExplainPojo = getFieldAttr(searchDataInConditionDTO);
                fieldAttrEntity = conditionExplainPojo.getParentFieldAttr();

                //开启了电话掩码的电话字段不支持筛选功能
                if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) && Objects.equals(searchDataInConditionDTO.getFormId(), 0L)
                        && Objects.equals(WorkOrderEnum.CONTACT_INFORMATION.getAttr(), searchDataInConditionDTO.getAttr())) {
                    // 全部工单列表筛选电话时特殊处理
                    Map<String, Object> param = new HashMap<>();
                    param.put("corpid", searchDataInConditionDTO.getCorpid());
                    param.put("del", 0);
                    param.put("enable", 1);
                    List<WorkOrderFormEntity> formList = workOrderFormModel.findEntitys(param);
                    if (CollectionsUtil.isNotEmpty(formList)) {
                        List<Long> formIdIn = formList.stream().map(WorkOrderFormEntity::getId).collect(Collectors.toList());
                        param.clear();
                        param.put("corpid", searchDataInConditionDTO.getCorpid());
                        param.put("del", 0);
                        param.put("formIdIn", formIdIn);
                        List<WorkOrderExplainEntity> explainList = workOrderExplainModel.findEntitys(param);
                        for (WorkOrderExplainEntity explain : explainList) {
                            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explain.getExplains());
                            FieldAttrEntity phoneField = explainMap.get(WorkOrderEnum.CONTACT_INFORMATION.getAttr());
                            boolean isOpenTelephoneMask = ExplainUtil.isOpenTelephoneMask(phoneField, searchDataInConditionDTO.getLoginUser());
                            if (isOpenTelephoneMask) {
                                throw new XbbException(ErrorCodeEnum.API_ERROR_352000);
                            }
                        }
                    }
                } else {
                    if (ExplainUtil.isOpenTelephoneMask(fieldAttrEntity, searchDataInConditionDTO.getLoginUser())) {
                        throw new XbbException(ErrorCodeEnum.API_ERROR_352000);
                    }
                }

                if (conditionExplainPojo.getIsSubForm()) {
                    fieldAttrEntity = conditionExplainPojo.getSubFieldAttr();
                }
                if((Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), CustomerManagementEnum.SCORE.getAttr()))||
                        (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.CLUE.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), ClueEnum.SCORE.getAttr()))){
                    if(CollectionsUtil.isEmpty(fieldAttrEntity.getItems())){
                        fieldAttrEntity.setItems(scoreRangeService.getItems4ScoreRangeScreen(searchDataInConditionDTO.getCorpid(),searchDataInConditionDTO.getFormId()));
                    }
                }
            }
            Boolean subAttr = false;
            if (StringUtil.isNotEmpty(searchDataInConditionDTO.getSubAttr())) {
                subAttr = true;
            }
            String corpid = searchDataInConditionDTO.getCorpid();
             switch (fieldTypeEnum) {
                case COMBO:
                case BUSINESS_TYPE:
                case RADIO_GROUP:
                case STAGE_THRUSTER:
                    ComboTypeEnum comboTypeEnum = ComboTypeEnum.getComboTypeEnum(fieldAttrEntity.getComboType());
                    switch (comboTypeEnum) {
                        case CUSTOM:
                            List<ItemDataPoJo> items = new ArrayList<>();
                            if (Objects.equals(searchDataInConditionDTO.getSubBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                                String[] fieldList = new String[]{StringConstant.SAAS_LINK_BUSINESS_ID, CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.NAME)};
                                IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

                                SearchRequest searchRequest = new SearchRequest(customerIndex.getIndex());
                                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                                BoolQueryBuilder boolQueryBuilder = boolQuery();
                                boolQueryBuilder.filter(termQuery("corpid.keyword", searchDataInConditionDTO.getCorpid()));
                                boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
                                if (Objects.nonNull(searchDataInConditionDTO.getValue()) && StringUtil.isNotEmpty(searchDataInConditionDTO.getValue().toString())) {
                                    boolQueryBuilder.filter(QueryBuilders.matchPhraseQuery(CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.NAME), searchDataInConditionDTO.getValue().toString()));
                                }
                                sourceBuilder.query(boolQueryBuilder);
                                sourceBuilder.fetchSource(fieldList, null);
                                //分页
                                sourceBuilder.from(0);
                                sourceBuilder.size(10);
                                searchRequest.source(sourceBuilder);
                                List<PaasFormDataEntity> content = xbbElasticsearchRestTemplate.queryForList(searchRequest, PaasFormDataEntity.class);
                                if (content != null) {
                                    for (PaasFormDataEntity paasFormDataEntity : content) {
                                        ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                                        itemDataPoJo.setText(paasFormDataEntity.getData().get(CustomerManagementEnum.NAME.getAttr()));
                                        itemDataPoJo.setValue(paasFormDataEntity.getId());
                                        items.add(itemDataPoJo);
                                    }
                                }
                            } else{
                                items = getCustomList(searchDataInConditionDTO, fieldAttrEntity, subAttr, conditionExplainPojo);
                            }
                            searchDataInConditionVO.setItems(items);
                            break;
                        case LINKFORM:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            TransmittableThreadLocalUtil.setValue(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getMenuId(), searchDataInConditionDTO.getDistributorMark());
                            searchDataInConditionVO = distinctDataService.listOfText(conditionExplainPojo,fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                            break;
                        case DATARELY:
                        case BUSINESS:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            TransmittableThreadLocalUtil.setValue(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getMenuId(), searchDataInConditionDTO.getDistributorMark());
                            searchDataInConditionVO = distinctDataService.listOfText(conditionExplainPojo,fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DATA_NOT_STANDARD);
                    }
                    break;
                case COMBO_CHECK:
                case CHECKBOX_GROUP:
                    ComboTypeEnum comboType = ComboTypeEnum.getComboTypeEnum(fieldAttrEntity.getComboType());
                    switch (comboType) {
                        case CUSTOM:
                            List<ItemDataPoJo> items = getCustomList(searchDataInConditionDTO, fieldAttrEntity, subAttr, conditionExplainPojo);
                            searchDataInConditionVO.setItems(items);
                            break;
                        case LINKFORM:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            TransmittableThreadLocalUtil.setValue(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getMenuId(), searchDataInConditionDTO.getDistributorMark());
                            searchDataInConditionVO = distinctDataService.listOfArray(fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                            break;
                        case DATARELY:
                        case BUSINESS:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            TransmittableThreadLocalUtil.setValue(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getMenuId(), searchDataInConditionDTO.getDistributorMark());
                            searchDataInConditionVO = distinctDataService.listOfArray(fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DATA_NOT_STANDARD);
                    }
                    break;
                case TEXT:
                    // todo 除序列号之外的其他单行文本字段
                    if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.SEQ_SEARCH.getCode())) {
                        Map<String, Object> serialParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        serialParam.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        serialParam.put(ParameterConstant.CORPID, searchDataInConditionDTO.getCorpid());
                        serialParam.put(ParameterConstant.COLUMNS, "seq");
                        serialParam.put("pageSize", 10);
                        serialParam.put("seq", searchDataInConditionDTO.getValue());
                        List<ProductSerialBalanceEntity> entitys = productSerialBalanceModel.findEntitys(serialParam);
                        List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                        List<String> seqList = new ArrayList<>();
                        for (ProductSerialBalanceEntity serialBalanceEntity : entitys) {
                            if (seqList.contains(serialBalanceEntity.getSeq())) {
                                continue;
                            }
                            seqList.add(serialBalanceEntity.getSeq());
                            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                            itemDataPoJo.setText(serialBalanceEntity.getSeq());
                            itemDataPoJo.setValue(serialBalanceEntity.getSeq());
                            itemDataPoJoList.add(itemDataPoJo);
                        }
                        searchDataInConditionVO.setItems(itemDataPoJoList);
                    } else if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                        Map<String, Object> param = new HashMap<>();
                        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        param.put(ParameterConstant.CORPID, searchDataInConditionDTO.getCorpid());
                        param.put("pageSize", 10);
                        param.put("nameLike", searchDataInConditionDTO.getValue());
                        param.put(ParameterConstant.COLUMNS, "name");
                        List<PriceSetEntity> entitys = priceSetModel.findEntitys(param);
                        List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                        List<String> priceNameList = new ArrayList<>();
                        for (PriceSetEntity priceSetEntity : entitys) {
                            if (priceNameList.contains(priceSetEntity.getName())) {
                                continue;
                            }
                            priceNameList.add(priceSetEntity.getName());
                            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                            itemDataPoJo.setText(priceSetEntity.getName());
                            itemDataPoJo.setValue(priceSetEntity.getName());
                            itemDataPoJoList.add(itemDataPoJo);
                        }
                        searchDataInConditionVO.setItems(itemDataPoJoList);
                    }  else if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.WRITE_OFF_RECORD.getCode())) {
                        Map<String, Object> param = new HashMap<>();
                        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        param.put(ParameterConstant.CORPID, searchDataInConditionDTO.getCorpid());
                        param.put("pageSize", 10);
                        param.put("nameLike", searchDataInConditionDTO.getValue());
                        param.put(ParameterConstant.COLUMNS, "name,id");
                        List<DistributorAccountEntity> entitys = distributorAccountModel.findEntitys(param);
                        List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                        for (DistributorAccountEntity priceSetEntity : entitys) {
                            ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                            itemDataPoJo.setText(priceSetEntity.getName());
                            itemDataPoJo.setValue(priceSetEntity.getId());
                            itemDataPoJoList.add(itemDataPoJo);
                        }
                        searchDataInConditionVO.setItems(itemDataPoJoList);
                    }else if(Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())){
                        if(Objects.equals(searchDataInConditionDTO.getAttr(), KnowledgeDataEnum.STATUS.getAttr())){
                            List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                            itemDataPoJoList.add(new ItemDataPoJo("停用",1));
                            itemDataPoJoList.add(new ItemDataPoJo("启用",0));
                            searchDataInConditionVO.setItems(itemDataPoJoList);
                        } else {
                            List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                            Map<String, Object> param = new HashMap<>();
                            param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                            param.put(ParameterConstant.CORPID, searchDataInConditionDTO.getCorpid());
                            param.put("pageSize", 10);
                            param.put("nameLike", searchDataInConditionDTO.getValue());
                            param.put("orderByStr", "update_time desc");
                            List<KnowledgeDataEntity> knowledgeDataEntities=knowledgeDataModel.findEntitys(param);
                            for (KnowledgeDataEntity knowledgeDataEntity : knowledgeDataEntities) {
                                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                                itemDataPoJo.setText(knowledgeDataEntity.getTitle());
                                itemDataPoJo.setValue(knowledgeDataEntity.getId());
                                itemDataPoJoList.add(itemDataPoJo);
                            }
                            searchDataInConditionVO.setItems(itemDataPoJoList);
                        }
                    }else {
                        saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                        searchDataInConditionVO = conditionListService.listOfText(conditionExplainPojo, fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                    }
                    break;
                 case LABEL:
                     if (Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())){
                         List<ItemDataPoJo> itemDataPoJoList = new ArrayList<>();
                         Map<String, Object> param = new HashMap<>();
                         param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                         param.put(ParameterConstant.CORPID, searchDataInConditionDTO.getCorpid());
                         param.put("parentType", 0);
                         param.put("pageSize", 10);
                         param.put("nameLike", searchDataInConditionDTO.getValue());
                         param.put("orderByStr", "update_time desc");
                         List<KnowledgeTagEntity> knowledgeTagEntities=knowledgeTagModel.findEntitys(param);
                         for (KnowledgeTagEntity knowledgeTagEntity : knowledgeTagEntities) {
                             ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                             itemDataPoJo.setText(knowledgeTagEntity.getName());
                             itemDataPoJo.setValue(knowledgeTagEntity.getId());
                             itemDataPoJoList.add(itemDataPoJo);
                         }
                         searchDataInConditionVO.setItems(itemDataPoJoList);
                     }else {
                         saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                         TransmittableThreadLocalUtil.setValue(searchDataInConditionDTO.getSaasMark(), searchDataInConditionDTO.getBusinessType(), searchDataInConditionDTO.getMenuId(), DistributorMarkEnum.OTHER.getCode());
                         searchDataInConditionVO = distinctDataService.listOfLabel(fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                     }
                     break;
                 case SCORE_RANGE:
                     searchDataInConditionVO = distinctDataService.listOfScoreRange(fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                     break;
                 case PUBLIC_GROUP:
                     searchDataInConditionVO = distinctDataService.listOfPublicGroup(fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                     break;
                default:
                    searchDataInConditionVO = getConditionDataList(conditionExplainPojo, fieldAttrEntity, searchDataInConditionDTO);
                    break;
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("proFormDataService.dataConditionList 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return searchDataInConditionVO;
    }

    /**
     * 获取ItemdataPojo for 新工单自定义报表
     * @param searchDataInConditionDTO
     * @return
     */
    private List<ItemDataPoJo> getItemData4NodeLogInfo(SearchDataInConditionDTO searchDataInConditionDTO) {
        List<ItemDataPoJo> res = new ArrayList<>();
        if (Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2_NODE_LOG_INFO.getCode(), searchDataInConditionDTO.getBusinessType())
                && Objects.equals(FieldTypeEnum.NODE_ID.getType(), searchDataInConditionDTO.getFieldType())) {
            Map<String, Object> param = new HashMap<>(16);
            param.put("userId", searchDataInConditionDTO.getUserId());
            param.put("corpid", searchDataInConditionDTO.getCorpid());
            param.put("page", 1);
            param.put("pageSize", 10);
            param.put("platform", searchDataInConditionDTO.getPlatform());
            param.put("versionId", searchDataInConditionDTO.getSpecialField());
            String nodeNameListResponse = workOrderClient.getNodeNameMap(param, LocaleContextHolder.getLocale().toString());
            XbbResponse response = JsonHelperUtil.parseObject(nodeNameListResponse, XbbResponse.class);
            JSONObject result = JsonHelperUtil.parseObject(response.getResult().toString());
            JSONArray nodeNamePojoList = result.getJSONArray("list");
            for (Object o : nodeNamePojoList) {
                JSONObject processNodePojo = (JSONObject) o;
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setText(processNodePojo.getString("name"));
                itemDataPoJo.setValue(processNodePojo.getString("id"));
                res.add(itemDataPoJo);
            }
        }
        return res;
    }

    /**
     * sla日志的部分下拉特殊处理
     * @param searchDataInConditionDTO 入参
     * @param items 筛选项
     */
    private void setSpecialItemsForSla(SearchDataInConditionDTO searchDataInConditionDTO,List<ItemDataPoJo> items) {
        // sla日志的部分下拉特殊处理
        if ("text_2".equals(searchDataInConditionDTO.getAttr())) {
            Map<String,Object> param = new HashMap<>(16);
            param.put("corpid",searchDataInConditionDTO.getCorpid());
            param.put("start",0);
            param.put("pageNum",10);
            param.put("businessType",XbbRefTypeEnum.WORK_ORDER_V2.getCode());
            param.put("nameLike",searchDataInConditionDTO.getValue());
            param.put("del",0);
            List<PaasFormEntityExt> formList = paasFormModel.findEntitys(param);
            for (PaasFormEntityExt paasFormEntityExt : formList) {
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setText(paasFormEntityExt.getName());
                itemDataPoJo.setValue(paasFormEntityExt.getId());
                items.add(itemDataPoJo);
            }
        } else if ("text_1".equals(searchDataInConditionDTO.getAttr())) {
            Map<String,Object> param = new HashMap<>(16);
            param.put("userId",searchDataInConditionDTO.getUserId());
            param.put("corpid",searchDataInConditionDTO.getCorpid());
            param.put("page",1);
            param.put("pageSize",10);
            param.put("platform",searchDataInConditionDTO.getPlatform());
            param.put("nameLike",searchDataInConditionDTO.getValue());
            String slaRuleListResponse = workOrderClient.slaRuleList(param, LocaleContextHolder.getLocale().toString());
            XbbResponse response = JsonHelperUtil.parseObject(slaRuleListResponse,XbbResponse.class);
            JSONObject result = JsonHelperUtil.parseObject(response.getResult().toString());
            JSONArray slaList = result.getJSONArray("list");
            for (Object o : slaList) {
                JSONObject sla = (JSONObject) o;
                ItemDataPoJo itemDataPoJo = new ItemDataPoJo();
                itemDataPoJo.setText(sla.getString("name"));
                itemDataPoJo.setValue(sla.getString("id"));
                items.add(itemDataPoJo);
            }
        }
    }


    @Override
    public SearchDataInConditionVO organizationConditionList(SearchInConditionDTO searchInConditionDTO) throws XbbException {
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(searchInConditionDTO.getFieldType());
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        switch (fieldTypeEnum) {
            case USER:
            case USER_GROUP:
            case CREATORID:
            case OWNERID:
            case COUSERID:
                searchDataInConditionVO = distinctDataService.listOfUser(searchInConditionDTO);
                break;
            case DEPT:
            case DEPT_GROUP:
            case DEPARTMENTID:
            case CREATOR_DEPT:
                searchDataInConditionVO = distinctDataService.listOfDepartment(searchInConditionDTO);
                break;
            default:
                break;
        }
        return searchDataInConditionVO;
    }

    @Override
    public SearchDataInConditionVO relClueDataConditionList(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        List<ItemDataPoJo> clueStatusItemList = new ArrayList<>();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(searchDataInConditionDTO.getFieldType());
        switch (fieldTypeEnum) {
            case COMBO:
                clueStatusItemList =  getClueStatusItemList();
            default:
                break;
        }
        searchDataInConditionVO.setItems(clueStatusItemList);
        return searchDataInConditionVO;
    }

    /**
     * 获取线索状态
     * @return
     */
    private List<ItemDataPoJo> getClueStatusItemList(){
        List<ItemDataPoJo> itemList = new ArrayList<>();
        ItemDataPoJo itemDataPoJo;
        for(ClueStatusEnum clueStatusEnum : ClueStatusEnum.values()){
            itemDataPoJo = new ItemDataPoJo();
            itemDataPoJo.setText(clueStatusEnum.getName());
            itemDataPoJo.setValue(clueStatusEnum.getCode());
            itemList.add(itemDataPoJo);
        }
        return itemList;
    }

    @Override
    public OtherDataListVO otherDataList(FormDataListDTO otherDataListDTO) throws XbbException {
        OtherDataListVO otherDataListVO = new OtherDataListVO();
        try {
            List<Long> dataIdList = otherDataListDTO.getIdIn();
            // 回收站和公海池，不需要在这边请求
            List<Integer> blockList = Arrays.asList(XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode(), XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode(), XbbRefTypeEnum.CLUE_PUBLIC.getCode(), XbbRefTypeEnum.CLUE_RECYCLE.getCode());
            if (CollectionsUtil.isEmpty(dataIdList) || blockList.contains(otherDataListDTO.getSubBusinessType())) {
                otherDataListVO.setPageHelper(new PageHelper());
                otherDataListVO.setPaasFormDataESList(new ArrayList<>());
                return otherDataListVO;
            }
            String corpid = otherDataListDTO.getCorpid();
            Integer businessType = otherDataListDTO.getBusinessType();
            Integer saasMark = otherDataListDTO.getSaasMark();
            boolean isProduct = Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode());
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, otherDataListDTO.getFormId(), businessType);
            List<FieldAttrEntity> explainList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            Iterator<FieldAttrEntity> iterator = explainList.iterator();
            SaasFieldConstant saasFieldConstant = new SaasFieldConstant();
            List<String> searchFieldList = new ArrayList<>();
            if (saasFieldConstant.getFieldMap().containsKey(businessType)) {
                searchFieldList = saasFieldConstant.getFieldMap().get(businessType);
            }
            while (iterator.hasNext()) {
                FieldAttrEntity fieldAttrEntity = iterator.next();
                if (searchFieldList.contains(fieldAttrEntity.getAttr())) {
                    fieldList.add(fieldAttrEntity.getAttr());
                    continue;
                }
                if (!Objects.equals(FieldTypeEnum.LINK_DATA.getType(), fieldAttrEntity.getFieldType()) && !Objects.equals(FieldTypeEnum.LINK_DATA_MULTI.getType(), fieldAttrEntity.getFieldType())) {
                    iterator.remove();
                    continue;
                }
                fieldList.add(fieldAttrEntity.getAttr());
            }

            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", otherDataListDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("formId", otherDataListDTO.getFormId()));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery("dataId", dataIdList));
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);

            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
            searchSourceBuilder.query(boolQueryBuilder);

            PaasFormDataEsListVO formDataEsListVO = paasEsModel.list(indexTypeEnum, businessType, searchSourceBuilder, fieldList, 1, dataIdList.size());
            formDataEsListVO.setHeadList(explainList);
            if (isProduct) {
                // 解析关联数据
                formDataLinkDataListAnalysisDataHelp.analysisDataList(otherDataListDTO, formDataEsListVO);
            }
            // 接下来开始搞操作
            AbstractOptionHandle abstractOptionHandle = optionFactory.getByBusinessType(businessType, saasMark);
            abstractOptionHandle.setOptionsInData(otherDataListDTO, formDataEsListVO);
            if (!isProduct) {
                // 解析关联数据
                formDataLinkDataListAnalysisDataHelp.analysisDataList(otherDataListDTO, formDataEsListVO);
            }
            otherDataListVO.setPaasFormDataESList(formDataEsListVO.getPaasFormDataESList());
            otherDataListVO.setPageHelper(formDataEsListVO.getPageHelper());
        } catch (Exception e) {
            LOG.error("proFormDataService.otherDataList 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return otherDataListVO;
    }

    @Override
    public LinkFormDataVO businessComboData(BusinessFormDataDTO businessFormDataDTO) throws XbbException{
        LinkFormDataVO formDataVO = new LinkFormDataVO();
        try {
            SearchDataInConditionDTO searchDataInConditionDTO = new SearchDataInConditionDTO();
            BeanUtil.copyProperties(businessFormDataDTO, searchDataInConditionDTO);
            SearchDataInConditionVO searchDataInConditionVO = distinctDataService.listOfBusiness(searchDataInConditionDTO);
            formDataVO.setItems(searchDataInConditionVO.getItems());
        } catch (Exception e) {
            LOG.error("proFormDataService.businessComboData 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataVO;
    }

    @Override
    public List<PaasFormDataEntityExt> dataListAndSubDataList(String corpid, Integer saasMark, Integer businessType, Long formId, List<Long> dataIdList) throws XbbException {
        //解析查询条件
        IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_FORM_DATA;
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            businessType = XbbRefTypeEnum.transferBusinessType2Index(businessType);
            indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);
        }
        List<PaasFormDataEntityExt> list = paasEsModel.dataListAndSubDataList(corpid, saasMark, businessType, formId, dataIdList, indexTypeEnum);
        // 设置子表单数据
        setSubFormData(list, corpid, saasMark, businessType, formId);
        return list;
    }

    @Override
    public void setSubFormData(List<PaasFormDataEntityExt> list, String corpid, Integer saasMark, Integer businessType, Long formId) throws XbbException{
        if (CollectionsUtil.isNotEmpty(list)) {
            Set<Long> resultDataIdList = new HashSet<>();
            list.forEach(item->{
                resultDataIdList.add(item.getDataId());
            });
           IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, businessType, saasMark);
           paasEsModel.setSubFormData(list, corpid, saasMark, businessType, formId, indexTypeEnum);
        }
    }



}
